//index.js
//获取应用实例
const app = getApp()
var level = require('../../utils/level.js');//导入等级数据列表
var config = require('../../utils/parts.js');//导入配件表
var md5 = require('../../utils/md5');
var header = getApp().request("header");
var requestUrl = getApp().request("url");
Page({
  data: {
    userInfo: {},
    baseRequestUrl:config.apiUrl,//线上接口地址
    baseImgUrl: config.imgUrl,//图片地址
    //==============================================================================
    carRank: '',
    carLevel: '',
    carName: 'SUV概念车',
    carIconUrl: '',
    //==============================================================================
    //图片路径部分
    imgUrl_a: '',
    imgUrl_b: '',
    imgUrl_c: '',
    imgUrl_d: '',
    imgUrl_e: '',
    imgUrl_f: '',
    imgUrl_g: '',
    //==============================================================================
    score: 0,//头部总分显示
    hasCar: false,//是否买过车
    hasChance: true,//当日是否可以等待时间再次抽奖
    carMsg: {},//车辆信息
    carArrName: 0,//车辆名车数组编号
    getCoinShow: false,//获取金币弹窗
    getBaoShow: false,//获取大通宝弹窗
    canPlay: true,//当日是否还能抽奖
    lastTime: '12：12',//抽奖等待时间
    chance: 0,//当日剩余抽奖机会
    goldcoin: 0,//用户金币数量
    bao: 0,//用户大通宝数量
    startPage:true,//引导页标号
    intro:false,
    gameIntroShow: false,//游戏说明弹出
    levelIntroShow: false,//等级说明弹窗
    levelItem: level.list,//等级信息列表
    coin2bao: false,//金币兑换大通宝
    coin2baoItem: 0,//金币兑换大通宝选中条目
    isLower: true,//底部scroll view是否滑动到最右,
    dtbArr:[5,25,50,250],
    indicatorDots: true, //轮播图的点
    indicator_color:"#535353",
    indicator_active_color: "#ffcc3f",
    autoplay: false,//自动轮播
    duration: 500,
    circular:true,
    success_gold:"1000",
    close_success:false,  //兑换成功
    noticeShow:false,
    prize: false,         //中奖名单
    prizeUrl:"",
    isIllustration: false,    //图鉴是否显示
    illustration: 1,           //图鉴参数,
    swiperId: 0          //图鉴滑动参数
  },
  //关闭按钮处理
  closeView: function (event) {
    var name = event.target.dataset.name;
    this.setData({
      [name]: false
    })
  },
  startPage:function(){
    wx.setStorage({
        key:'intro',
        data:false
    });
    this.setData({
      intro:false
    })
    this.notice();
    wx.setStorageSync("noticeTime",parseInt(new Date().getTime()/1000))
  },
  notice(){
    var that=this;
    wx.request({
      url: requestUrl + 'notice',
      method: "GET",
      header: header,
      success: function (res) {
        console.log(res);
        if (res.data.code == 200) {
          that.setData({
            prize:true,
            prizeUrl: res.data.data.notice
          })
        }else if (res.data.code == 800) {
          getApp().showModal(res.data.data.msg);
          wx.hideLoading();
        } 
      },
      fail: function (res) {
       
      }
    })
  },
  noticeShow:function(){
    //点击活动公告
    this.setData({
      noticeShow:true
    });
  },
  toBuyCarPage: function () {
    //前往买车页面
    wx.redirectTo({
      url: '../buy/buy'
    })
  },
  toDutyPage: function () {
    //前往每日任务页面
    wx.navigateTo({
      url: '../dayTask/dayTask'
    })
  },
  toMyRankPage:function(){
    //前往排名页面
    wx.navigateTo({
      //url: '../myRank/myRank'
      url:'../notice/notice'
    })
  },
  toCollegePage: function () {
    //前往SUV学院页面
    wx.navigateTo({
      url: '../college/college'
    })
  },
  toStorePage: function () {
    //前往商店
    wx.navigateTo({
      url: '../store/store'
    })
  },
  toLotteryPage: function () {
    var depot = app.globalData.depot;
    if(Object.keys(depot).length>=48){
      wx.showToast({
        title: '仓库已满,请先卖出多余配件',
        icon: 'none'
      })
      return false;
    }
    if (app.globalData.fightCarTypeId== 0) {
      getApp().showModal("请先购买车辆哦！")
      return false
    }
    //前往抽奖页面
    wx.navigateTo({
      url: '../lottery/lottery'
    })
  },
  toRepackCarPage: function () {
    //前往装配页面
    wx.redirectTo({
      url: '../repack/repack'
    });
  },
  //打开按钮处理
  openView: function (event) {
    var name = event.target.dataset.name;
    this.setData({
      [name]: true
    })
  },
  //底部按钮滚动事件
  lower: function () {
    this.setData({
      isLower: false
    })
  },
  upper: function () {
    this.setData({
      isLower: true
    })
  },
  //打开金币兑换大通宝页面
  tocoin2bao: function () {
    this.setData({
      getCoinShow: false,
      coin2bao: true
    })
    // wx.showToast({
    //   title:'敬请期待',
    //   icon:'none'
    // })
  },
  toWarehousePage(){
    //前往仓库页面
    this.setData({
      getCoinShow:false
    })
    wx.navigateTo({
      url:'../warehouse/warehouse'
    })
  },
  //金币兑换大通宝选项逻辑
  coin2bao: function (event) {
    var num = event.target.dataset.num;
    if (this.data.coin2baoItem == num) {
      this.setData({
        coin2baoItem: 0
      })
    } else {
      this.setData({
        coin2baoItem: num
      })
    }
  },
  //立即兑换大通宝按钮
  btnNowExchange(){
    var that=this;
    //未选中金币不能兑换
    if (this.data.coin2baoItem==0){return}
    var dtbArr=this.data.dtbArr;     //大通宝数组
    var dtbItem = this.data.coin2baoItem - 1;  //选中的哪个大通宝
    var dtbNum = dtbArr[dtbItem];              //选中的大通宝数量
    //请求大通宝和是否登录
    wx.showLoading({
      title: ' ',
      mask:true
    })
    wx.request({
      url: requestUrl + 'baoExchangeGold',
      method: "POST",
      data: { userId: app.globalData.session_key.userId, salt: app.globalData.session_key.salt, bao: dtbNum},
      header: header,
      success: (res) => {
        if (res.data.code == 200) {
          //data大金币数量增加
          var goldcoin = this.data.goldcoin;
          goldcoin += dtbNum * 200;
          //本地存储的金币相应增加
          //wx.setStorageSync("gold", goldcoin)
          app.globalData.gold = goldcoin;
          this.setData({
            coin2bao: false,   //关闭窗口
            coin2baoItem: 0,    //大通宝选项初始化
            goldcoin: goldcoin,  //金币数量
            success_gold: dtbNum*200,
            close_success:true
          });
        } else if (res.data.code == 402) {
          getApp().showModal("提交大通宝数量有误！");
        } else if (res.data.code == 401 || res.data.code == 301 || res.data.code == 302) {
          getApp().showModal("系统信息有误，请重试！");
        } else if (res.data.code == 304) {
          getApp().showModal("大通宝余额不足！");
        } else if (res.data.code == 305) {
          getApp().showModal("大通宝余额不足！");
        } else if (res.data.code == 306) {
          getApp().showModal("大通宝兑换金币失败，请重试！");
        } else if (res.data.code == 303) {
          wx.navigateTo({
            url: '../login/login?url=index'
          })
        } else if (res.data.code == 800) {
          getApp().showModal(res.data.data.msg);
          wx.hideLoading();
        }
        wx.hideLoading();
      },
      fail:function(res){
        console.log("大通宝接口失败fail");
        console.log(res);
        wx.hideLoading();
        getApp().showModal("网络超时，请检查您的网络");
      }
    });
  },
  computedLastTime: function () {
    //计算抽奖剩余时间
  },
  onShow: function (options) {
    wx.showShareMenu({
      withShareTicket: true
    });
    var _this = this,
      userId = app.globalData.session_key.userId,
      salt = app.globalData.session_key.salt;
    wx.showLoading({
      title: '',
      mask:true
    })  
    // 生命周期函数--监听页面加载
    if (salt!="" && userId!=0){
      
      var nickName = wx.getStorageSync("nickName");
      var avatarUrl = wx.getStorageSync("avatarUrl");
      if (nickName == ""){
        wx.navigateTo({
          url: "/pages/authorize/authorize"
        });
        return false;
      }
      app.globalData.nickName=wx.getStorageSync("nickName");
      app.globalData.avatarUrl = wx.getStorageSync("avatarUrl");
      wx.checkSession({
        success: function (res) {
          console.log(app.globalData.nickName);
          _this.setData({
            userInfo: {
              nickName: nickName,
              avatarUrl: avatarUrl
            }
          });
          wx.request({
            url: _this.data.baseRequestUrl + 'synInfo',
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: {
              userId: userId,
              salt: salt
            },
            success: function (res) {
              console.log(res);
              if (res.statusCode != 200) {
                getApp().showModal("服务器异常");
                return
              }
              if (res.data.code == 200) {
                //判断是否有车
                console.log("请求synInfo成功");
                if (res.data.data.car != '') {
                  //使用信息渲染页面
                  var paiqi = _this.getImgUrl(res.data.data.car[0].f),
                    lungu = _this.getImgUrl(res.data.data.car[0].c),
                    penqi = _this.getImgUrl(res.data.data.car[0].b),
                    taban = _this.getImgUrl(res.data.data.car[0].g),
                    lahua = _this.getImgUrl(res.data.data.car[0].a),
                    xingli = _this.getImgUrl(res.data.data.car[0].e),
                    baoxian = _this.getImgUrl(res.data.data.car[0].d);
                  _this.setData({
                    score: res.data.data.car[res.data.data.fightCarTypeId - 1].score,
                    carMsg: res.data.data.car,
                    imgUrl_f: paiqi,
                    imgUrl_c: lungu,
                    imgUrl_b: penqi,
                    imgUrl_g: taban,
                    imgUrl_a: lahua,
                    imgUrl_e: xingli,
                    imgUrl_d: baoxian,
                    chance: res.data.data.drawLeftN
                  })
                  //本地存储用户信息
                  app.globalData.score = res.data.data.car[res.data.data.fightCarTypeId - 1].score;
                  app.globalData.drawLeftN = res.data.data.drawLeftN;
                  app.globalData.shareLeftN = res.data.data.shareLeftN;
                  app.globalData.juniorGiftBoxN = res.data.data.juniorGiftBoxN;
                  app.globalData.middleGiftBoxN = res.data.data.middleGiftBoxN;
                  app.globalData.seniorGiftBoxN = res.data.data.seniorGiftBoxN;
                  app.globalData.car = res.data.data.car;
                  app.globalData.depot = res.data.data.depot;
                  //分析分数，获取车辆名称
                  _this.doScoreAnalysis(res.data.data.car[res.data.data.fightCarTypeId - 1].score);
                } else {
                  //没车时
                  console.log(res.data.data);
                  _this.setData({
                    hasCar: false,
                    chance: res.data.data.drawLeftN,
                    goldcoin: res.data.data.gold,
                    car: res.data.data.car,
                    score: 0
                  })
                  var no_car_arr = [{ "a": "", "b": "", "c": "", "d": "", "e": "", "f": "", "g": "", "h": "" }];
                  app.globalData.drawLeftN = res.data.data.drawLeftN;
                  app.globalData.score = 0;
                  app.globalData.car = no_car_arr;
                  app.globalData.depot = res.data.data.depot;
                  app.globalData.juniorGiftBoxN = res.data.data.juniorGiftBoxN;
                  app.globalData.middleGiftBoxN = res.data.data.middleGiftBoxN;
                  app.globalData.seniorGiftBoxN = res.data.data.seniorGiftBoxN;
                  app.globalData.shareLeftN = res.data.data.shareLeftN;
                  app.globalData.bindPhone = res.data.data.bindPhone;
                }
                app.globalData.gold = res.data.data.gold;
                app.globalData.fightCarTypeId = res.data.data.fightCarTypeId;
                // 返回页面同步数据
                var fightCarTypeId = app.globalData.fightCarTypeId,
                  goldcoin = app.globalData.gold,
                  score = app.globalData.score,
                  car_type = app.globalData.car,
                  drawLeftN = app.globalData.drawLeftN,
                  car = app.globalData.car;
                app.globalData.car_name = "SUV概念车";
                var car_name = app.globalData.car_name;
                if (car_type[0]) {
                  var carArrName = Number(car_type[0].type)
                }
                if (_this.data.fightCarTypeId == 0) return;
                if (_this.data.hasCar === false && fightCarTypeId != 0) {
                  _this.setData({
                    hasCar: true
                  })
                }
                if (car[0]) {
                  var a = _this.getImgUrl(car[0].a),
                    b = _this.getImgUrl(car[0].b),
                    c = _this.getImgUrl(car[0].c),
                    d = _this.getImgUrl(car[0].d),
                    e = _this.getImgUrl(car[0].e),
                    f = _this.getImgUrl(car[0].f),
                    g = _this.getImgUrl(car[0].g);

                  _this.setData({
                    goldcoin: goldcoin,
                    score: score,
                    carArrName: carArrName,
                    chance: drawLeftN,
                    imgUrl_a: a,
                    imgUrl_b: b,
                    imgUrl_c: c,
                    imgUrl_d: d,
                    imgUrl_e: e,
                    imgUrl_f: f,
                    imgUrl_g: g,
                    car_name: "SUV概念车"
                  })
                }
                _this.doScoreAnalysis(score);
                wx.hideLoading();
              } else if (res.data.code == 800) {
                getApp().showModal(res.data.data.msg);
                wx.hideLoading();
              } else {
                getApp().showModal("同步信息失败");
                console.log('%c同步信息失败!\n' + res.data.code, 'background:rgba(0,0,0,0.1);color:red');
              }

            },
            fail: function (res) {
              console.log(res);
              getApp().showModal("网络奔溃啦，请关闭后重试哦！");
            }
          });
        },
        fail: function () {
          wx.navigateTo({
            url: "/pages/authorize/authorize"
          });
        }
      });
    }else{
      wx.navigateTo({
        url:"/pages/authorize/authorize"
      });
      //获取用户信息
      
    }
  },
  doScoreAnalysis: function (num) {
    if (num == '') return;
    //分析分数,获取车名
    var index = parseInt(num / 15000);
    if (index > 34) index = 34;
    var nameArr = ['SUV概念车', '越野一族', '商务座驾'];
    var arr = ['青铜级,lv1,level-qt.png', '青铜级,lv2,level-qt.png', '青铜级,lv3,level-qt.png', '青铜级,lv4,level-qt.png', '青铜级,lv5,level-qt.png',
      '白银级,lv1,level-by.png', '白银级,lv2,level-by.png', '白银级,lv3,level-by.png', '白银级,lv4,level-by.png', '白银级,lv5,level-by.png',
      '黄金级,lv1,level-hj.png', '黄金级,lv2,level-hj.png', '黄金级,lv3,level-hj.png', '黄金级,lv4,level-hj.png', '黄金级,lv5,level-hj.png',
      '铂金级,lv1,level-bj.png', '铂金级,lv2,level-bj.png', '铂金级,lv3,level-bj.png', '铂金级,lv4,level-bj.png', '铂金级,lv5,level-bj.png',
      '钻石级,lv1,level-zs.png', '钻石级,lv2,level-zs.png', '钻石级,lv3,level-zs.png', '钻石级,lv4,level-zs.png', '钻石级,lv5,level-zs.png',
      '大师级,lv1,level-ds.png', '大师级,lv2,level-ds.png', '大师级,lv3,level-ds.png', '大师级,lv4,level-ds.png', '大师级,lv5,level-ds.png',
      '王者级,lv1,level-wz.png', '王者级,lv2,level-wz.png', '王者级,lv3,level-wz.png', '王者级,lv4,level-wz.png', '王者级,lv5,level-wz.png'];

    var res = arr[index].split(',');

    this.setData({
      carRank: res[0],
      carLevel: res[1],
      carIconUrl: this.data.baseImgUrl + '/' + res[2]
    })
  },
  getImgUrl: function (str) {
    if (str == '') return '';
    return this.data.baseImgUrl + '/parts/' + str[0] + '/' + str + '_big.png';
  },
  setStorage: function (name, data) {
    //设置本地存储
    wx.setStorage({
      key: name,
      data: data,
      success: function () {
        console.log("%c存储用户" + name + "成功", 'background:#017b40;color:#fff');
      },
      fail: function (res) {
        console.log('%c存储用户' + name + '失败!\n' + res, 'background:rgba(0,0,0,0.1);color:red');
      }
    })
  },
  onReady: function () {
    this.setData({
      loading:false
    });
    // 生命周期函数--监听页面初次渲染完成
  },
  onLoad: function () {
    var _this=this;
    //查看本地存储是否进入过游戏,控制显示游戏规则
    wx.getStorage({
      key: 'intro',
      success: function (res) {
         _this.setData({
           intro: false
         })
      },
      fail:function(){
        _this.setData({
          intro: true
        })
      }
    });
    //显示公告 没小时显示一次
    if (wx.getStorageInfoSync().keys.indexOf("intro") != -1){
      var Time = parseInt(new Date().getTime() / 1000);
      if (Time-wx.getStorageSync("noticeTime")>36000){
        this.notice();
        wx.setStorageSync("noticeTime", Time)
      }
    }
    // 生命周期函数--监听页面显示
    
  },
  onHide: function () {
    // 生命周期函数--监听页面隐藏
  },
  onUnload: function () {
    // 生命周期函数--监听页面卸载
  },
  //pk分享
  onShareAppMessage: function (res) {
    var _this = this;
    var userId = app.globalData.session_key.userId,
        key = 'puzzleidea666';
    var shareToken = md5(md5(userId + key) + key);
    var path = '/pages/pk/pk?shareId=' + userId + '&shareToken=' + shareToken;
    console.log(path);
    if (res.from === 'button') {
      return {
        title: '定制车神，快来比比谁的车更牛',
        path: path,
        success: function (res) {
        },
        fail: function (res) {
          // 转发失败
        }
      }
    }else{
      var that = this;
      //是否选车
      var fightCarTypeId = app.globalData.fightCarTypeId;
      //随机一句宣言
      var declaration = getApp().Refit();
      var myRefitTxt = Math.floor(Math.random() * declaration.length);
      if (fightCarTypeId == 0) {
        return {
          title: getApp().shareTitle1(),
          path: "/pages/index/index"
        }
      } else {
        console.log("分享到那里去了")
        return {
          title: getApp().shareTitle2(),
          path: "/pages/openShare/openShare?shareId=" + app.globalData.session_key.userId + "&carTypeId=" + fightCarTypeId + "&shareRefitNum=" + myRefitTxt + "&carName=SUV概念车",
          success: function (re) {
            console.log(re)
            if (Object.keys(re).length==1){
              return
            }
            var ticket = re.shareTickets[0];
            wx.getShareInfo({
              shareTicket: ticket,
              success: function (Re) {
                console.log(Re)
                var encryptedData = Re.encryptedData;
                var iv = Re.iv;
                //请求分享接口加次数
                wx.showLoading({
                  title: '',
                  mask:true
                });
                wx.request({
                  url: requestUrl + 'shareGroupAddDrawNum',
                  method: "POST",
                  data: { userId: app.globalData.session_key.userId, salt: app.globalData.session_key.salt, encryptedData: encryptedData, iv: iv },
                  header: header,
                  success: function (Res) {
                    console.log(Res);
                    if (Res.data.code == 200) {
                      //当日剩余抽取次数减去一
                      var shareLeftN = app.globalData.shareLeftN;
                      shareLeftN--;
                      //wx.setStorageSync("shareLeftN", shareLeftN);
                      app.globalData.shareLeftN = shareLeftN;
                      //剩余抽取次数加3次
                      var drawLeftN = app.globalData.drawLeftN;
                      drawLeftN += 3;
                      app.globalData.drawLeftN = drawLeftN;
                      //wx.setStorageSync("drawLeftN", drawLeftN);
                      //页面分享进度减一
                      // var shareProgress = that.data.shareProcess;
                      //  shareProgress++;
                      that.setData({
                        chance: that.data.chance + 3
                      });
                    } else if (Res.data.code == 401 || Res.data.code == 301 || Res.data.code == 302) {
                      getApp().showModal("提交信息有误!")
                    } else if (Res.data.code == 304) {
                      //getApp().showModal("解密错误!")
                      getApp().sessionKey()
                    } else if (Res.data.code == 800) {
                      getApp().showModal(Res.data.data.msg);
                      wx.hideLoading();
                    }
                    wx.hideLoading();
                  },
                  fail:function(res){
                    console.log("分享次数接口fail");
                    console.log(res)
                    wx.hideLoading();
                    getApp().showModal("网络超时，请检查您的网络");
                  }
                })
              }
            })
          }
        }
      }
    }
    
  },
  btnClosePrize(){
     this.setData({
       prize:false
     })
  },
  //点击显示图鉴
  btn_showIllustrate() {
    this.setData({
      isIllustration: true
    })
  },
  //点击隐藏图鉴
  btn_hideIllustrate() {
    this.setData({
      isIllustration: false,
      illustration: 1,
      swiperId:0
    })
  },
  //图鉴切换
  btnSwitchIllustration(e) {
    var illustrate = e.target.dataset.illustrate;
    this.setData({
      illustration: illustrate,
      swiperId: illustrate - 1
    })
  },
  changeSwiper(e) {
    console.log(e.detail.current)
    var changeId = e.detail.current;
    this.setData({
      illustration: changeId + 1,
      swiperId: changeId
    })
  }
})
